<template>
  <a-spin :spinning="loading || selfLoading">
    <a-card size="small" :title="title">
      <div>
        <a-row type="flex" style="margin-bottom:10px" :gutter="16" >
          <a-col :span="4">教师姓名</a-col>
          <a-col :span="4">兼课学院</a-col>
          <a-col :span="4">角色</a-col>
          <a-col :span="4">执笔字数(万)</a-col>
          <a-col :span="4">积分</a-col>
          <a-col :span="2">删除</a-col>
        </a-row>

        <a-row type="flex" v-for="(item, index) in value" :key="index" :gutter="16">
          <a-form-model :ref="getRef(index)" style="width: 100%" :model="value[index]" :rules="rules">
            <a-form-model-item style="display: none">
              <a-input placeholder="id" v-model="item.id" />
              <a-input-number placeholder="排名" v-model="item.ranked" @blur="rankedChange" :disabled="disabled"></a-input-number>
            </a-form-model-item>

            <a-col :span="4">
              <a-form-model-item class="gfxy-item" prop="teacherId">
                <j-select-user-by-dep  v-model="item.teacherId" @change="(...args)=>{selectedUser(...args,index)}" :multi="false" :disabled="disabled"></j-select-user-by-dep>
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item class="gfxy-item" prop="orgId_dictText">
                <a-input placeholder="所属学院" v-model="item.orgId_dictText" :disabled="true"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item class="gfxy-item" prop="role">
                <j-dict-select-tag type="list" v-model="item.role" dictCode="RESEARCH_ZZJC_ROLE" placeholder="请选择角色" />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item class="gfxy-item" prop="count">
                <a-input-number :min="0" placeholder="执笔字数" :step="0.01" :precision="2"  v-model="item.count" />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item class="gfxy-item" prop="score">
                <a-input-number :min="0" placeholder="积分" :step="0.01" :precision="2"  v-model="item.score"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item class="gfxy-item">
                <a-popconfirm title="确定删除该教师？" @confirm="delRow(index)" okText="确定" cancelText="取消" :disabled="disabled">
                  <a-icon type="minus-circle" style="fontSize :20px;color: #faad14"/>
                </a-popconfirm>
              </a-form-model-item>
            </a-col>
          </a-form-model>
        </a-row>
        <a-button type="dashed" style="width: 100%;margin-top: 10px;margin-bottom: 10px" @click="addMember" :disabled="disabled">
          <a-icon type="plus" /> 添加成员
        </a-button>
      </div>
    </a-card>
  </a-spin>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getAction, postAction } from '@api/manage'

export default {
  name: "memberList",
  props: {
    title:{
      type: String,
      required: false,
      default: '成员列表'
    },
    value:{
      type: Array,
      required:true
    },
    projectInfo:{
      type: Object,
      required:true
    },
    disabled:{
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },

  },
  model:{
    prop: "value",
    event: "change"
  },

  data() {

    return {
      selfLoading: false,
      scoreEditable: false,
      rules: {
        ranked: [{required: true,message: '请输入排名',trigger: 'blur'}],
        teacherId: [{required: true,message: '请选择教师',trigger: 'blur'}],
        orgId_dictText: [{required:true, message:'请关联分院'}],
        score:[{required:true, message:'请输入积分'}]
      } ,
      url: {
        getDepUrl:"/gfxy/common/queryDepartmentByUserName",
        getScore:"/research/researchCommon/memberListScores"
      },
    }
  },
  computed: {
    computeColor: function(){
      let color = this.actualTotalScore > this.totalScore ? 'red' : '#1890FF';
      return {
        color: color,
        fontWeight: 600
      };
    },
    actualTotalScore: function(){
      let result = 0.0;
      let that = this
      this.value.forEach((item)=>{
        result = this.$math.add(result , item.score)
      })
      return this.$math.round(result, 2);
    },
    isCustomTranslator: function(){
      let result = false;
      if(this.value.isCustom == 1){
        result = true;
      }
      return result;
    }
  },
  watch: {
    value:{
      deep:true,
      handler: function(val,oldVal){
        this.onChange();
      }
    },
    // 'projectInfo.totalScore':{
    //   immediate: true,
    //   handler: function(newVal,oldVal){
    //     console.log(newVal, oldVal)
    //     // this.getScore();
    //   }
    // }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    // //---------------------------- begin 图片左右换位置 -------------------------------------
    this.headers = {"X-Access-Token":token};
    this.containerId = 'container-ty-'+new Date().getTime();

  },
  methods: {
    getScore(){
      if(this.value.length!=0){
        this.selfLoading = true;
        getAction(this.url.getScore ,{projectType: this.projectInfo.projectType, totalScore: this.projectInfo.totalScore , memeberNum: this.value.length}).then((res)=>{
          if(res.success){
            console.log(res.result);
            this.value.forEach((item,index)=>{
              console.log(item, index)
              item.score = res.result.scores[index];
            })
          }else{
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.selfLoading = false;
          console.log("finally")
        })
      }

    },
    rankedChange(){
      this.sortValue()
      this.getScore()
    },
    onScoreEditableChange(checked){

      this.scoreEditable = checked
      this.value.forEach(item=>{
        item.isCustom = checked ? 1:0;
      })
    },

    sortValue(){
      this.value.sort(function(a, b){
        return a.ranked - b.ranked;
      })
    },
    getRef(index){
      return 'formref_' + index
    },
    addMember (){
      this.value.push({ranked:this.value.length+1,orgId:'',orgId_dictText:'',proportion:0.0,isCustom:this.scoreEditable?1:0, score:0,projectType:this.projectInfo.projectType,date:this.projectInfo.date})
      this.sortValue()
      this.getScore()
    },
    delRow(index){
      this.value.splice(index,1);
      for(let i=1 ; i<=this.value.length ; i++){

        this.value[i-1].ranked = i;
      }
      this.sortValue()
      this.getScore()

    },
    selectedUser(name,id,index){
      console.log(this.value)
      let teacherId = this.value[index].teacherId;
      let isExist = this.value.find((v,i) => {
        if(i!=index){
          return v.teacherId == teacherId;
        } else {
          return false;
        }
      })
      console.log(isExist)
      if(isExist === undefined){
        console.log("选择的用户为：" + teacherId);
        this.queryTeachingDep(index,teacherId);
      } else {
        console.log(this.value[index])
        this.$error({
          title: '重复添加用户',
          content: "用户：" + name + "[" + id + "] 已经添加",
        });
      }
    },
    queryTeachingDep(index,teacherId){
      console.log(this.url.getDepUrl)
      getAction(this.url.getDepUrl ,{userName: teacherId}).then((res)=>{
        if(res.success){
          console.log(res.result);
          this.value[index].orgId = res.result.orgCode;
          this.value[index].orgId_dictText = res.result.departName;
          console.log(this.value[index])
        }else{
          this.$message.warning(res.message);
        }
      }).finally(() => {
        console.log("finally")
      })
    },
    onChange(){
      console.log("onChange")
      if(this.value.length > 0){
        this.scoreEditable = this.value[0].isCustom==1? true: false
      }

      this.$emit("change", this.value)
    },
    validateList() {

      let result = true;
      for (let key in this.$refs) {

        if(this.$refs[key].length !=0 && typeof this.$refs[key][0].validate === 'function'){
          this.$refs[key][0].validate(valid => {
            result = result && valid;
            return;
          })
        }
      }
      return result;
    }
  },
  mounted() {


  },
  updated: function () {
    this.$nextTick(()=>{

      this.validateList();

    })
  }
}
</script>

<style scoped>
.gfxy-item{
  margin-top:5px;
}
.ant-row {
  margin-bottom: 0;
}
</style>